import requests,json,os,time
from urllib.parse import urlencode

def getImg(page,headers):
    '''
    获取百度街拍URL
    '''
    url = 'http://image.baidu.com/search/acjson?tn=resultjson_com&ipn=rj&ct=201326592&is=&fp=result&queryWord=%E8%A1%97%E6%8B%8D&cl=2&lm=-1&ie=utf-8&oe=utf-8&adpicid=&st=&z=&ic=&word=%E8%A1%97%E6%8B%8D&s=&se=&tab=&width=&height=&face=&istype=&qc=&nc=&fr=&pn='+ str(page) +'&rn=30'
    try:
        res = requests.get(url,headers = headers)
        if res.status_code == 200:
            content = res.content.decode('utf-8')
            myjson = json.loads(content)
            '''
            将图片连接和名字存到数组 photos中
            '''
            photos = []
            for i in range(0,len(myjson['data'])-1):
                photo = {'name': myjson['data'][i]['fromPageTitleEnc'],
                         'img' : myjson['data'][i]['thumbURL']}
                photos.append(photo)
            return photos
        else:
            print("Get Page Error!")
            return None
    except:
        return None
                
def saveImg(photos,headers):
    '''
    保存图片
    '''
    #图片保存路径
    path = os.path.join(os.getcwd(),'mypic')
    if not os.path.exists(path):
        os.mkdir(path)

    for photo in photos:
        save_pic = os.path.join(path,photo['name'].replace(' ','')+'.png')
        print(save_pic)
        print(photo['img'])
        try:
            with requests.get(photo['img'],stream=True,headers=headers) as ir:
                with open(save_pic,'wb') as w:
                    for chunk in ir:
                        w.write(chunk)
        except Exception as Error:
            print(Error + '\n保存图片失败')
            

def main(offset,headers):

    photos = getImg(offset,headers)
    saveImg(photos,headers)

if __name__ == "__main__":
    headers = {
        'Accept': 'application/json, text/javascript, */*; q=0.01',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Cookie': 'BAIDUID=66E9E57F31CE378F9842115CCE213895:FG=1; BIDUPSID=66E9E57F31CE378F9842115CCE213895; PSTM=1530790089; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; PSINO=7; BDSFRCVID=-SLsJeCCxG37Dv57hG45WOIxs0CH6AQX2liC3J; H_BDCLCKID_SF=tbkD_C-MfIvhDRTvhCcjh-FSMgTBKI62aKDssxO1-hcqEpO9QT-bQb50jU7xtTQUB25OQKJnWIQNVfP4h-rTDUTh-p52f6LtJbu83J; BDRCVFR[dG2JNJb_ajR]=mk3SLVN4HKm; BDRCVFR[-pGxjrCMryR]=mk3SLVN4HKm; BDRCVFR[tox4WRQ4-Km]=mk3SLVN4HKm; indexPageSugList=%5B%22%E8%A1%97%E6%8B%8D%22%5D; cleanHistoryStatus=0; H_PS_PSSID=1433_26260_26458_21113_22158',
        'Host': 'image.baidu.com',
        'Proxy-Connection': 'keep-alive',
        'Referer': 'http://image.baidu.com/search/index?tn=baiduimage&ps=1&ct=201326592&lm=-1&cl=2&nc=4&ie=utf-8&word=%E8%A1%97%E6%8B%8D',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',
        'X-Requested-With': 'XMLHttpRequest',
    }
    print("正在保存百度街拍前3页图片,请稍等..")
    #main(30,headers)
    for i in range(1,4):
        print('...')
        main(i*30,headers)
        time.sleep(3)
    print("已完成，请查看当前mypic目录文件。")

